#!/usr/bin/env python3
# start_services.py

import subprocess
import time
import sys
import os
from pathlib import Path

def start_redis():
    """启动Redis服务"""
    print("正在启动Redis服务...")
    try:
        # 检查Redis是否已运行
        result = subprocess.run(['redis-cli', 'ping'], capture_output=True, text=True)
        if result.returncode == 0:
            print("Redis服务已在运行")
            return True
        
        # 启动Redis
        subprocess.Popen(['redis-server'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        time.sleep(2)
        
        # 验证Redis是否启动成功
        result = subprocess.run(['redis-cli', 'ping'], capture_output=True, text=True)
        if result.returncode == 0:
            print("Redis服务启动成功")
            return True
        else:
            print("Redis服务启动失败")
            return False
    except Exception as e:
        print(f"启动Redis时发生错误: {e}")
        return False

def start_celery_worker():
    """启动Celery Worker"""
    print("正在启动Celery Worker...")
    try:
        # 启动Celery Worker
        worker_process = subprocess.Popen([
            'celery', '-A', 'celery_app', 'worker',
            '--loglevel=info',
            '--concurrency=4',  # 并发数
            '--pool=prefork'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        time.sleep(3)
        
        if worker_process.poll() is None:
            print("Celery Worker启动成功")
            return worker_process
        else:
            print("Celery Worker启动失败")
            return None
    except Exception as e:
        print(f"启动Celery Worker时发生错误: {e}")
        return None

def start_celery_monitor():
    """启动Celery Monitor"""
    print("正在启动Celery Monitor...")
    try:
        monitor_process = subprocess.Popen([
            'celery', '-A', 'celery_app', 'flower',
            '--port=5555'
        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        
        time.sleep(2)
        
        if monitor_process.poll() is None:
            print("Celery Monitor启动成功 (http://localhost:5555)")
            return monitor_process
        else:
            print("Celery Monitor启动失败")
            return None
    except Exception as e:
        print(f"启动Celery Monitor时发生错误: {e}")
        return None

def start_upload_api():
    """启动文件上传API"""
    print("正在启动文件上传API...")
    try:
        api_process = subprocess.Popen([
            'python', 'upload_api.py'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        time.sleep(3)
        
        if api_process.poll() is None:
            print("文件上传API启动成功 (http://localhost:8000)")
            return api_process
        else:
            print("文件上传API启动失败")
            return None
    except Exception as e:
        print(f"启动文件上传API时发生错误: {e}")
        return None

def start_rag_api():
    """启动RAG问答API"""
    print("正在启动RAG问答API...")
    try:
        api_process = subprocess.Popen([
            'python', 'multimodal_rag_api.py'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        time.sleep(3)
        
        if api_process.poll() is None:
            print("RAG问答API启动成功 (http://localhost:8001)")
            return api_process
        else:
            print("RAG问答API启动失败")
            return None
    except Exception as e:
        print(f"启动RAG问答API时发生错误: {e}")
        return None

def main():
    """主函数"""
    print("=== 多模态RAG系统服务启动器 ===")
    
    # 创建必要的目录
    os.makedirs("uploads", exist_ok=True)
    os.makedirs("uploads/images", exist_ok=True)
    os.makedirs("uploads/frames", exist_ok=True)
    os.makedirs("logs", exist_ok=True)
    
    processes = []
    
    try:
        # 1. 启动Redis
        if not start_redis():
            print("Redis启动失败，退出")
            return
        
        # 2. 启动Celery Worker
        worker_process = start_celery_worker()
        if worker_process:
            processes.append(("Celery Worker", worker_process))
        
        # 3. 启动Celery Monitor
        monitor_process = start_celery_monitor()
        if monitor_process:
            processes.append(("Celery Monitor", monitor_process))
        
        # 4. 启动文件上传API
        upload_process = start_upload_api()
        if upload_process:
            processes.append(("文件上传API", upload_process))
        
        # 5. 启动RAG问答API
        rag_process = start_rag_api()
        if rag_process:
            processes.append(("RAG问答API", rag_process))
        
        print("\n=== 所有服务启动完成 ===")
        print("服务地址:")
        print("- 文件上传API: http://localhost:8000")
        print("- RAG问答API: http://localhost:8001")
        print("- Celery Monitor: http://localhost:5555")
        print("\n按 Ctrl+C 停止所有服务")
        
        # 等待用户中断
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n正在停止所有服务...")
        
        # 停止所有进程
        for name, process in processes:
            print(f"正在停止 {name}...")
            try:
                process.terminate()
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
            except Exception as e:
                print(f"停止 {name} 时发生错误: {e}")
        
        print("所有服务已停止")

if __name__ == "__main__":
    main() 